<?php
/*
Description: A PHP class to import XYS article into Wordpress-based Lyceum blog system.
Author: Xuefeng LIU, xfliu.math@gmail.com 
	Graduate School of Mathematical Sciences, The University of Tokyo,
	153-8914, Japan	

How to use it:

* Download this file form http://www.xys-reader.org/o/xys_article.tar.gz;
* Extract the file "xys_article.php" out from this package and put it into the following path:
  <lyceum folder>wp-admin/import (After 1.0)
  <lyceum folder>lib/wp-admin/import (Before 1.0)

Copyright: This code is free of charge. Anyone can change it and distribute it again with this copyright info inside.

The author does not take any responsibility for the running results of this code.

Date: 2008/05/10

*/

error_reporting(E_ERROR | E_PARSE);
error_reporting( E_PARSE);

class XYS_Import {

	var $posts = array ();
	var $uid;
	var $file;
	var $Articles;
	
	function ReadURL($URL,$id=0)
	{
		$aurl=fopen($URL."&only_data=1","r");
		stream_set_timeout($aurl, 5);
		if(!$aurl) return NULL;
		while(!feof($aurl)){
			$search_str.=fgets($aurl,4096);
		}
		fclose($aurl);

		$search_str = iconv("GBK","UTF-8",$search_str);

		echo "<br>\n Reading URL :$URL<br>\n";

		$search_array=split("\n",$search_str);
		$i=0;
		$this->Articles=NULL;
		foreach($search_array as $line){
		if(preg_match('/Id:\s?([^\s]+)\s?Title:\s?([^\s]+)\s?Author:\s?([^\s]+)\s?Date:\s?(\d+)/',$line,$re)){
			$arc=NULL;
			$arc["id"]=$re[1];
			$arc["title"]=$re[2];
			$arc["author"]=$re[3];
			$arc["date"]=substr($re[4],0,4)."-".substr($re[4],4,2)."-".substr($re[4],6,2);
			if($arc["id"]) $this->Articles[$i++]=$arc;
		}
          }
	}

	function header() {
		echo '<div class="wrap">';
		echo '<h2>'.__('Import XYS articles').'</h2>';
	}

	function footer() {
		echo '</div>';
	}

	function unhtmlentities($string) { // From php.net for < 4.3 compat
		return $string;
	}

	function greet() {
		global $wpdb,$blog,$user, $current_user;
		$my_user_ID=$_GET["user_id"];


		echo "<!-- Hi, $my_user_ID --->";

		echo '<p>'.__('Howdy! This importer allows you to import XYS article! ').'</p>';
		echo '<form  method="post" action="admin.php?import=xys_article&step=1">';

		if($current_user->user_admin){
			echo __("Set the author of imported article to be:");
			echo ' <input name="user_ID" value="'; 
			echo $my_user_ID;
			echo '" type="text" size=3>';	
			echo " (Please input user id here. Default user is the admin. )";
			echo "<br><br>";
		}
		else {
			echo '<input name="user_ID" value="';
			echo $my_user_ID;
			echo '" type="hidden">';
		}
		
		echo _('Please input the url of search result at <a href="http://www.xys-reader.org">http://www.xys-reader.org</a>'); 
		echo '
		<br><br>
	<div id="buttons">
	<label for="upload">';
		echo 'URL: </label>
 <br><input id="upload" name="import_url" size=60 type="text" value="http://www.xys-reader.org/xys/p_search.php?linked=1&key_au=&key_title=%D0%C2%D3%EF%CB%BF%B6%C1%D5%DF%CD%F8"><br>
		Sample URL:
<a href="http://www.xys-reader.org/xys/p_search.php?key_title=%D0%C2%D3%EF%CB%BF%B6%C1%D5%DF%CD%F8">http://www.xys-reader.org/xys/p_search.php?key_title=%D0%C2%D3%EF%CB%BF%B6%C1%D5%DF%CD%F8 </a>

';
		echo '<input name="action" value="save" type="hidden">';
		echo '<br><br>',_('The category to be imported to:'),'<br>';
		echo '<select name="import_cat"> ';
  		wp_dropdown_cats(0);   
		echo '</select><br> ';
		echo '<br>',_('Only do test before importing articles.'),' <input name="test" value="1" type="checkbox" checked><br><br>';
	
		echo ' &nbsp;<input value="'. __('Test') . '" type="submit" name="test">
		&nbsp; &nbsp; <input value="'. __('Import It Now!') . '" type="submit">
	</div>
	</form>
<br>
<br>
		<hr size=1 width=80% align=left>';
		echo ' Created by Liu Xuefeng for XYS-READER BLOG, 2008/05<br>
If you have any problem during the importing, please contact with xfliu.math@gmail.com; ';
	}

	function get_posts($URL,$cat_ID) {
		
		global $wpdb;
		global $user_ID;

		$post_cat=get_catname($cat_ID);

//		set_time_limit(50);

		$my_user_ID=$_POST["user_ID"];
		if(!$my_user_ID) $my_user_ID=$user_ID;
		
//		set_magic_quotes_runtime(0);

		$fetech_url="http://www.xys-reader.org/xys/import_fetech.php?id=";

		$this->ReadURL($URL);
		echo "<br> ".__("Categories") . ": $post_cat <br>\n ";

		foreach( $this->Articles as $arc){

			$post_title0 = trim($arc["title"]);
			$post_title = $wpdb->escape(trim($arc["title"]));
			$post_date = $arc["date"];

			$i_str=$i+1; if($i_str<10) $i_str="0".$i_str;
			echo "<br>\n [$i_str] : Date:",$post_date, "&nbsp; ",$post_title0, " -> ".__("Categories") . ": $post_cat <br>\n ";

			$URL=$fetech_url.$arc["id"];
			$body="";
			$aurl=fopen($URL,"r");
			stream_set_timeout($aurl, 5);
			while(!feof($aurl) ) $body.=fgets($aurl,4096); fclose($aurl);
			$post_content=$body;
			echo mb_strlen($body)." bytes readed.<br>\n ";
							
			$categories = NULL;
			$categories[0] = $wpdb->escape($this->unhtmlentities($post_cat));
			/* ----------------------------------------------------
			// preparation for inserting into database.
			----------------------------------------------------  */							
			$guid = '';

			// Clean up content
			//$post_content = str_replace('\n', "<br />\n", $post_content);
			$post_content = "<pre>\n$post_content\n</pre>";

			$post_author = $my_user_ID;
			$post_status = 'publish';
							
			$this->posts = compact('post_author', 'post_date','post_date_gmt', 'post_content', 'post_title', 'post_status', 'guid', 'categories');

			if(!$_POST['test']) $this->import_posts();

			/* ----------------------------------------------------
			// preparation for inserting into database. OVER
			----------------------------------------------------  */						
				
			$i++;
		}
		if(!$_POST['test']) echo "<br>"._('Finished')."\n ";
		else
			echo "<br>",_("Test finished. Nothing imported for the moment.");

	}

	function import_posts() {

			$post=$this->posts;

			extract($post);
			
			if($post_title and $post_content){

				if ($post_id = post_exists($post_title, $post_content)) {

					if($_POST['my_update_post']){
						$post["ID"]=$post_id;
						if (!$post_id=wp_update_post($post)) {
							_e("Couldn't update this post");
							return;
						}
						_e(" updating ");
					}
					else{
						_e('Post already imported');
						return;
					}
				} else {
					if (!$post_id=wp_insert_post($post)) {
						_e("Couldn't get post ID");
						return;
					}

					if (0 != count($categories) )
						wp_create_categories($categories, $post_id);
				}
			}
		echo " [ ";
		_e('Done !');
		echo " ]";


	}
	function import() {
		$file = wp_import_handle_upload();
		$this->get_posts($_POST['import_url'],$_POST['import_cat']);
		wp_import_cleanup($file['id']);
		
		echo '<h3>';
		if(!$_POST['test'])
			printf(__('All done. <a href="%s">Have fun!</a>'), get_option('home'));
		else
			echo '<INPUT TYPE="button" VALUE="Go Back" onClick="history.back()">';
		echo '</h3>';
	}

	function dispatch() {
		if (empty ($_GET['step']))
			$step = 0;
		else
			$step = (int) $_GET['step'];

		$this->header();
		
		switch ($step) {
			case 0 :
				$this->greet();
				break;
			case 1 :
				$this->import();
				break;
		}
		
		$this->footer();
	}

	function XYS_Import() {
		// Nothing.	
	}
}

$xys_import = new XYS_Import();

register_importer('xys_article', 'XYS', __('Import articles of http://WWW.XYS.ORG'), array ($xys_import, 'dispatch'));
?>
